package com.sodaopen.study.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.sodaopen.study.entity.Chapter;
import com.sodaopen.study.entity.Course;
import com.sodaopen.study.entity.Media;
import com.sodaopen.study.entity.Stage;
import com.sodaopen.study.entity.Step;
import com.sodaopen.study.entity.Teacher;
import com.sodaopen.study.entity.User;
import com.sodaopen.study.service.ChapterService;
import com.sodaopen.study.service.CourseService;
import com.sodaopen.study.service.MediaService;
import com.sodaopen.study.service.StageService;
import com.sodaopen.study.service.StepService;
import com.sodaopen.study.service.TeacherService;

@Controller
public class IndexController {

    @Autowired
    private StageService stageService;

    @Autowired
    private CourseService courseService;

    @Autowired
	private ChapterService chapterService;

    @Autowired
	private TeacherService teacherService;

    @Autowired
	private MediaService mediaService;

    @Autowired
	private StepService stepService;

    @GetMapping("/")
    public String index(Model model){
        List<Stage> list = stageService.findAll();
        model.addAttribute("stageList", list);
        return "index";
    }
    
    @GetMapping("/stage/{id}")
    public String showStage(@PathVariable(name="id")Integer id, Model model, HttpSession session){
        Stage stage = stageService.findById(id);
        model.addAttribute("stage", stage);
        
        User user = (User)session.getAttribute("loginUser");

        List<Course> courseList = courseService.findByStageId(id, user.getId());
        model.addAttribute("courseList", courseList);

        return "stage";
    }
    
    
    @GetMapping("/course/{id}")
    public String showCourse(@PathVariable(name="id")Integer id, Model model, HttpSession session){
        Course course = courseService.findById(id);
        System.out.println(course);
        model.addAttribute("course", course);

        User user = (User)session.getAttribute("loginUser");
        List<Chapter> chapterList = chapterService.findLevelChapterByCourseIdFinish(id, user.getId());
        model.addAttribute("chapterList", chapterList);
        
        Teacher teacher = teacherService.findById(course.getTeacherId());
        model.addAttribute("teacher", teacher);
        return "course";
    }
    
    @GetMapping(value = {"/course/{id}/learning"})
    public String learning(@PathVariable(name="id") Integer id,
    		Model model, HttpSession session){
        Course course = courseService.findById(id);
        model.addAttribute("course", course);

        User user = (User)session.getAttribute("loginUser");
        List<Chapter> chapterList = chapterService.findLevelChapterByCourseIdFinish(id, user.getId());
        model.addAttribute("chapterList", chapterList);

        //默认打开第一个没有完成的章节
        Chapter currentChapter = chapterService.findCurrentChapter(chapterList);
        model.addAttribute("currentChapter", currentChapter);
        
        return "learning";
    }
    
    @GetMapping("/chapter/{id}")
    public String showChapter(@PathVariable(name="id")Integer id, Model model, HttpSession session){
    	User user = (User)session.getAttribute("loginUser");

    	Chapter chapter = chapterService.findByIdFinish(id, user.getId());
    	model.addAttribute("chapter", chapter);


    	//打开没有学完的课程，需要先检查课程是否有被锁定
        if("N".equals(chapter.getFinished())) {
            Map map = chapterService.findLockedByPrimaryKey(user.getId(), chapter.getCourseId());

            if (map != null && map.get("chapter_id") != chapter.getId()) {  //map不为空，而且被锁的章节ID不是当前请求的章节ID
                return "locked";
            }else if(map == null && "Y".equals(chapter.getLocked())){ //无锁，而且当前请求的章节需要加锁
                chapterService.lockUserChapter(user.getId(), chapter.getCourseId(), chapter.getId());
            }
        }

        //加载视频
    	if(chapter.getMediaId() != null) {
            Media media = mediaService.findById(chapter.getMediaId());
            try {
                media.setUrl(Base64.getEncoder().encodeToString(media.getUrl().getBytes("utf-8")));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            model.addAttribute("media", media);
        }

    	//加载步骤
    	List<Step> stepList = stepService.findByChapterId(id);
    	model.addAttribute("stepList", stepList);
    	
        return "chapter";
    }

}
